package com.hue.gulimailseckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hue.common.to.SeckillOrderTo;
import com.hue.common.utils.R;
import com.hue.common.vo.UserVo;
import com.hue.gulimailseckill.feign.CouponFeignService;
import com.hue.gulimailseckill.feign.ProduceFeignService;
import com.hue.gulimailseckill.interceptor.LoginStatusInterceptor;
import com.hue.gulimailseckill.service.SeckillService;
import com.hue.gulimailseckill.vo.SeckillRedisVo;
import com.hue.gulimailseckill.vo.SeckillSessionVo;
import com.hue.gulimailseckill.vo.SeckillSkuRelationVo;
import com.hue.gulimailseckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 姚凤桥
 * @Date 2022/1/12 11:01
 * @Description:
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    private static final String SECKILL_SESSION_PREFIX = "seckill:sessions:";
    private static final String SECKILL_SKU_PREFIX = "seckill:skus:";
    private static final String SECKILL_STOCK_PREFIX = "seckill:stock:";
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProduceFeignService produceFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void upload3Days() {
        R r = couponFeignService.getSeckill3Days();
        if ((Integer) r.get("code") == 0) {
            List<SeckillSessionVo> seckillSessions = r.getData(new TypeReference<List<SeckillSessionVo>>() {
            });

            //以活动时间为key将活动的skuId存储到redis中
            saveSessionSkuIds(seckillSessions);

            //存储skuInfo信息
            saveSessionSkuInfo(seckillSessions);

            //将活动标记为已经发布
            List<Long> ids = seckillSessions.stream().map(SeckillSessionVo::getId).collect(Collectors.toList());
            couponFeignService.setSessionPublish(ids);
        }
    }

    @Override
    public List<SeckillRedisVo> getSeckillProduce() {
        long nowTime = new Date().getTime();
        //获取所有已经发布的秒杀活动
        Set<String> sessionKeys = redisTemplate.keys(SECKILL_SESSION_PREFIX + "*");
        for (String sessionKey : sessionKeys) {
            String[] times = sessionKey.split(":")[2].split("_");
            //只对已经开始并且还没有结束的活动做查询操作
            if (Long.parseLong(times[0]) <= nowTime && Long.parseLong(times[1]) >= nowTime) {
                //获取当前场次的所有商品信息
                List<String> skuIds = redisTemplate.opsForList().range(sessionKey, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);
                List<String> produces = ops.multiGet(skuIds);

                if (produces != null) {
                    List<SeckillRedisVo> redisVos = produces.stream().map(produce -> {
                        SeckillRedisVo seckillRedisVo = JSON.parseObject(produce, SeckillRedisVo.class);
                        return seckillRedisVo;
                    }).collect(Collectors.toList());
                    return redisVos;
                }
            }
        }

        return new ArrayList<>();
    }

    @Override
    public SeckillRedisVo skuInfoSeckill(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);
        Set<String> keys = ops.keys();
        for (String key : keys) {
            String reg = "\\d_" + skuId;
            if (key != null && key.matches(reg)) {
                String json = ops.get(key);
                SeckillRedisVo seckillRedisVo = JSON.parseObject(json, SeckillRedisVo.class);

                //只有在秒杀时间内才返回随机码
                long now = new Date().getTime();
                if (!(now >= seckillRedisVo.getStartTime() && now <= seckillRedisVo.getEndTime())) {
                    seckillRedisVo.setRandomCode(null);
                }

                return seckillRedisVo;
            }
        }
        return null;
    }

    @Override
    public String kill(String key, String code) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);

        String json = ops.get(key);
        if (StringUtils.isEmpty(json)) {
            return null;
        }

        SeckillRedisVo seckillRedisVo = JSON.parseObject(json, SeckillRedisVo.class);
        //判断时间是否合法
        long now = new Date().getTime();
        if (now >= seckillRedisVo.getStartTime() && now <= seckillRedisVo.getEndTime()) {
            //判断随机码是否正确
            if (seckillRedisVo.getRandomCode().equals(code)) {
                //判断用户是否秒杀过(使用userId_sessionId_skuId来当作key,默认value为每个人只能抢购1件)
                UserVo user = LoginStatusInterceptor.threadLocal.get();

                //setIfAbsent()等于redis的setnx操作，当key不存在的时候设置，存在的时候不设置，返回boolean值，设置过期时间
                Long ttl = seckillRedisVo.getEndTime() - new Date().getTime();
                Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(user.getId() + "_" + key, "1", ttl, TimeUnit.MILLISECONDS);

                //当用户没有抢购过才执行抢购操作
                if (ifAbsent) {
                    //获取分布式信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_PREFIX + code);
                    try {
                        boolean acquire = semaphore.tryAcquire(1, 100, TimeUnit.MILLISECONDS);
                        if (acquire) {
                            //获取到信号量之后代表秒杀成功，将用户信息，sku信息，活动信息发送给rabbitmq，等待创建订单
                            String orderSn = IdWorker.getTimeId();
                            SeckillOrderTo seckillOrder = new SeckillOrderTo();
                            seckillOrder.setOrderSn(orderSn);
                            seckillOrder.setMemberId(user.getId());
                            seckillOrder.setPromotionSessionId(seckillRedisVo.getPromotionSessionId());
                            seckillOrder.setSkuId(seckillRedisVo.getSkuId());
                            seckillOrder.setSeckillPrice(seckillRedisVo.getSeckillPrice());
                            seckillOrder.setCount(1);

                            //给mq发送订单消息
                            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.queue",seckillOrder);

                            return orderSn;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return null;
    }

    /**
     * 将活动的skuId存储到redis中
     *
     * @param sessions
     */
    private void saveSessionSkuIds(List<SeckillSessionVo> sessions) {
        if (sessions == null && sessions.size() == 0) {
            return;
        }

        for (SeckillSessionVo session : sessions) {
            String key = SECKILL_SESSION_PREFIX + session.getStartTime().getTime() + "_" + session.getEndTime().getTime();
            List<String> skuIds = session.getSkuRelations().stream().map(relation -> session.getId() + "_" + relation.getSkuId()).collect(Collectors.toList());
            redisTemplate.opsForList().leftPushAll(key, skuIds);
        }
    }

    /**
     * 将活动的skuInfo存储到redis中
     *
     * @param sessions
     */
    private void saveSessionSkuInfo(List<SeckillSessionVo> sessions) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SECKILL_SKU_PREFIX);

        //获取所有的skuInfo
        R r = produceFeignService.getAll();
        if ((Integer) r.get("code") == 0) {
            List<SkuInfoVo> skuInfos = r.getData(new TypeReference<List<SkuInfoVo>>() {
            });

            //将skuInfos转换为Map
            Map<Long, SkuInfoVo> skuInfoMap = skuInfos.stream().collect(Collectors.toMap(SkuInfoVo::getSkuId, skuInfo -> skuInfo));

            //存储所有参加秒杀活动的skuInfo
            for (SeckillSessionVo session : sessions) {
                for (SeckillSkuRelationVo skuRelation : session.getSkuRelations()) {
                    SeckillRedisVo seckillRedisVo = new SeckillRedisVo();
                    //设置商品的sku详情
                    seckillRedisVo.setSkuInfoVo(skuInfoMap.get(skuRelation.getSkuId()));

                    //设置商品的活动信息
                    BeanUtils.copyProperties(skuRelation, seckillRedisVo);

                    //设置商品秒杀的开始时间和结束时间
                    seckillRedisVo.setStartTime(session.getStartTime().getTime());
                    seckillRedisVo.setEndTime(session.getEndTime().getTime());

                    //设置商品秒杀的随机码
                    seckillRedisVo.setRandomCode(UUID.randomUUID().toString().replace("-", ""));

                    //设置商品的信号量，来代表商品的数量
                    RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_PREFIX + seckillRedisVo.getRandomCode());
                    semaphore.trySetPermits(seckillRedisVo.getSeckillCount().intValue());

                    //将SeckillRedisVo保存到redis的hash表中
                    ops.put(session.getId() + "_" + skuRelation.getSkuId(), JSON.toJSONString(seckillRedisVo));
                }
            }
        }
    }
}
